package com.atguigu01.string.exer2;

import com.sun.xml.internal.fastinfoset.util.CharArray;
import org.junit.Test;

/**
 * ClassName: PersonTest
 * Description:
 *
 * @Author liu
 * @Create 2024/11/20 21:45
 * @Version 1.0
 */
public class StringTest {

    /**
     * 将一个字符串进行反转。将字符串中指定部分进行反转。
     * 比如"abcdefg"反转为"abfedcg"
     */
    //法一
    public String reverse1(String str, int start, int end) {
        if (str != null) {
            char[] arr = str.toCharArray();
            for (int i = start, j = end; i < j; i++, j--) {
                char temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
            return new String(arr);//匿名实例
        }
        return null;
    }

    //法二
    public String reverse2(String str, int start, int end) {
        //1.
        String newStr = str.substring(0,start);//ab
        //2.从后往前插入字符
        for (int i = end ; i >=start ; i--) {
            newStr +=str.charAt(i);
        }//abfedc
        //3.
        newStr += str.substring(end+1);//从g开始
        return newStr;
    }

    //法三
      public String reverse3(String str, int start, int end) {
        StringBuilder s = new StringBuilder(str.length());
        s.append(str.substring(0,start));
          for (int i = end; i >= start ; i--) {
              s.append(str.charAt(i));
          }
          s.append(str.substring(end+1));
          return s.toString();
      }
    @Test
    public void test1(){
      String str = "abcdefg";
       String str1 = reverse2(str, 2, 5);
        System.out.println(str1);

    }


    /**
     * 获取一个字符串在另一个字符串中出现的次数。
      比如：获取"ab"在 "abkkcadkabkebfkabkskab" 中出现的次数
     */
    public int getCount(String mainStr,String subStr){
        if(mainStr.length() >= subStr.length()){
            int count = 0;
            int index = 0;

            while ((index = mainStr.indexOf(subStr,index)) !=-1){
                //indexOf()-->找到目标字符并返回下标，没找到返回-1
                index +=subStr.length();
                count++;
            }
            return count;
        }else{
            return 0;
        }

    }

@Test
public void test2(){
  String s1 = "abkkcadkabkebfkabkskab" ;//main
  String s2 = "ab";//subStr
    int num = getCount(s1,s2);
    System.out.println(num);
}
}
